<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\facade\Config;
use think\facade\Db;

/**
 * 首页接口
 */
class Crud extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $table = 'fa_test';

    protected $relation = ['category'];

    /**
     * 首页
     *
     */
    public function index()
    {
        $data = [];
        $req = json_decode('{ "table": "adfesse", "list": [ { "title": "单行文本", "field": "input_1562735091000_72876", "attr": "CHAR(10)", "icon": "icon-input", "filter-render": { "name": "input", "width": "100%", "defaultValue": "", "required": false, "dataType": "string", "pattern": "", "placeholder": "", "disabled": false, "remoteFunc": "func_1562735091000_72876" }, "key": "1562735091000_72876", "rules": [] }, { "title": "单行文本", "field": "input_1562735087000_28441", "attr": "CHAR(10)", "icon": "icon-input", "filter-render": { "name": "input", "width": "100%", "defaultValue": "", "required": false, "dataType": "string", "pattern": "", "placeholder": "", "disabled": false, "remoteFunc": "func_1562735087000_28441" }, "key": "1562735087000_28441", "rules": [] }, { "title": "单选框组", "field": "radio_1562735084000_17140", "attr": "ENUM", "icon": "icon-radio-active", "filter-render": { "name": "radio", "inline": false, "defaultValue": "", "showLabel": false, "required": false, "width": "", "remote": false, "remoteOptions": [], "props": { "value": "value", "label": "label" }, "remoteFunc": "func_1562735084000_17140", "disabled": false }, "filters": [ { "value": "选项1", "label": "选项1" }, { "value": "选项2", "label": "选项2" }, { "value": "选项3", "label": "选项3" } ], "key": "1562735084000_17140", "rules": [] }, { "title": "时间选择器", "field": "time_1562729255000_54035", "attr": "TIME", "icon": "icon-time", "filter-render": { "name": "time", "props": { "format": "HH:mm:ss", "startPlaceholder": "", "endPlaceholder": "", "clearable": true }, "defaultValue": "21:19:56", "readonly": false, "disabled": false, "editable": true, "placeholder": "", "isRange": false, "arrowControl": true, "required": false, "width": "", "remoteFunc": "func_1562729255000_54035" }, "key": "1562729255000_54035", "rules": [] }, { "title": "下拉选择框", "field": "select_1562729262000_35515", "attr": "INT(1)", "icon": "icon-select", "filter-render": { "name": "select", "defaultValue": "", "multiple": false, "disabled": false, "clearable": false, "placeholder": "", "required": false, "showLabel": false, "width": "", "remote": false, "filterable": false, "remoteOptions": [], "props": { "value": "value", "label": "label" }, "remoteFunc": "func_1562729262000_35515" }, "filters": [ { "value": "下拉框1" }, { "value": "下拉框2" }, { "value": "下拉框3" } ], "key": "1562729262000_35515", "rules": [] } ], "config": { "labelWidth": 100, "labelPosition": "right", "size": "small" } }', true);
//        $req = json_decode(file_get_contents('php://input'), true);


        if(empty($req)|| empty($req['list'])){
            $this->error('数据为空');
        }


        $array = [];
        $table = [];

        $array = array_merge($array, $req['list']);
        while ($array) {
            $tmp = array_shift($array);
            if ($tmp['filter-render']['name'] == 'grid') {
                foreach ($tmp['columns'] as $columns) {
                    $array = array_merge($array, $columns['list']);
                }
            } else {
                $def = '';
                $setmenu = '';

                if ($tmp['filter-render'] && $tmp['filter-render']['defaultValue']) {
                    $def = $tmp['filter-render']['defaultValue'];
                }
                if (!empty($tmp['filter-render']['remote']) && $tmp['filter-render']['remote']) {
                    foreach ($tmp['filters'] as $options) {

                    }
                } else {
                    if ((strcasecmp($tmp['attr'], 'ENUM') == 0 || strcasecmp($tmp['attr'], 'SET') == 0)) {
//                        print_r($tmp['filters']);
//                        array_column($tmp['filters'],'value')
                        $filtersVal = array_column($tmp['filters'], 'value');
                        $setmenu = '(' .
//                           "'" . join("','", array_values($filtersVal) ) . "'"//#join
//                           "'".str_replace( ",","','", implode(',',$filtersVal))."'"
                            join(',', array_map(function ($v) {
                                return "'" . $v . "'";
                            }, $filtersVal))
//                       implode(',',$filtersVal)
                            . ')';

                        if (strcasecmp($tmp['attr'], 'ENUM') == 0) {
                            $def = empty($def) ? array_shift($filtersVal) : '';
                        }

                    }
                }

                if (empty($def)){
                    $isint = ['int','MEDIUMINT','TINYINT','SMALLINT'];
                    foreach ($isint as $i){
                        if (stripos(  $tmp['attr'],$i)=== 0){
                            $def = 0;
                            break;
                        }
                    }
                }


                $table[$tmp['field']] = '`' . $tmp['field'] . '` ' . $tmp['attr'] . $setmenu . ' NOT NULL DEFAULT \'' . $def . '\' COMMENT \'' . $tmp['title'] . '\'';

            }
        }
        $dbconnect = Db::connect(Config::get('database.default'));
        $getConfig = $dbconnect->getConfig();


        //从数据库中获取表字段信息
        $sql = "SELECT * FROM `information_schema`.`columns` "
            . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
            . "ORDER BY ORDINAL_POSITION";

        //加载主表的列

        if (empty($req['table'])) $this->error('表名不能为空');
        $tableName = '';
        $prefix = $getConfig['prefix'];
        if (strpos( $req['table'],$prefix)=== 0){
            $tableName = $req['table'];
        }else{
            $tableName = $prefix . $req['table'];
        }
        $columnList = $dbconnect->query($sql, [$getConfig['database'], $tableName]);

        $sql = '';
        if (empty($columnList)) {
//           $sql= ' DROP TABLE IF EXISTS `' . $tableName . '`;';
            $sql .= ' CREATE TABLE `' . $tableName . '` (';
            $sql .= implode(',', array_values($table));

            $sql .= ') ENGINE=InnoDB  DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT ;';

            die($sql);
            $dbconnect->execute($sql);
        } else {
            $columnName = array_column($columnList, 'COLUMN_NAME');

            //添加字段
            foreach ($table as $field => $fieldVal) {
                if (!in_array($field, $columnName)) {

                    $sql = 'ALTER TABLE ' . $tableName . ' ADD ' . $fieldVal . ' ;';

                    $dbconnect->execute($sql);
                }
            }
        }

        $data['controllerName'] = ucfirst(ltrim($tableName,$prefix));
        $data['tableComment'] = $tableName;
        $data['jsonData'] = var_export($req['list'], true) ;
        //缓存

        $this->writeToFile( $data);
//        $this->success('请求成功', $columnList);
    }




    /**
     * 写入到文件
     * @param string $name
     * @param array  $data
     * @param string $pathname
     * @return mixed
     */
    protected function writeToFile( $data)
    {
        foreach ($data as $index => &$datum) {
            $datum = is_array($datum) ? '' : $datum;
        }
        unset($datum);
        $content = $this->getReplacedStub( $data);
        $pathname = __DIR__.DIRECTORY_SEPARATOR.$data['controllerName'].'.php';

        if (!is_dir(dirname($pathname))) {
            mkdir(dirname($pathname), 0755, true);
        }
        return file_put_contents($pathname, $content);
    }

    /**
     * 获取替换后的数据
     * @param string $name
     * @param array  $data
     * @return string
     */
    protected function getReplacedStub($data)
    {
        foreach ($data as $index => &$datum) {
            $datum = is_array($datum) ? '' : $datum;
        }
        unset($datum);
        $search = $replace = [];
        foreach ($data as $k => $v) {
            $search[] = "{%{$k}%}";
            $replace[] = $v;
        }
        $stubname  = app()->getAppPath().DIRECTORY_SEPARATOR .'library'.DIRECTORY_SEPARATOR.'traits'.DIRECTORY_SEPARATOR.'stubs'.DIRECTORY_SEPARATOR.'controller.sub';

        if (isset($this->stubList[$stubname])) {
            $stub = $this->stubList[$stubname];
        } else {
            $this->stubList[$stubname] = $stub = file_get_contents($stubname);
        }
        $content = str_replace($search, $replace, $stub);
        return $content;
    }

    /**
     * 获取基础模板
     * @param string $name
     * @return string
     */
    protected function getStub($name)
    {
        return __DIR__ .  DIRECTORY_SEPARATOR  . 'Crud' .  DIRECTORY_SEPARATOR  . 'stubs' .  DIRECTORY_SEPARATOR  . $name . '.stub';
    }

}
